package lottery

import (
	"database/sql"
	"errors"
	"geak/biz/m"
	"geak/libs/ecode"
	"geak/libs/log"
	ts "geak/tools/strings"
	"go.uber.org/zap"
	"strings"
	"fmt"
)

func (this *Service)GetLastestDLT()(dlt *m.Lottery,err error) {

	dltList,err := this.GetDLTList(0,1)
	if err != nil {
		return nil,err
	}
	if len(dltList) == 1 {
		return dltList[0],nil
	}else {
		return nil,errors.New("query rows len > 1")
	}


}

func (this *Service)GetDLTList(start int64,count int64)(dltList []*m.Lottery,err error)  {

	sqlStr := fmt.Sprintf("SELECT `code`,`date`,`red`,`blue`,`blue2`,`sales`,`pool_money`,`first_count`," +
		"`first_money`,`second_count`,`second_money`,`third_count`,`third_money` FROM `dlt` " +
		"ORDER BY `code` DESC LIMIT %d,%d",start,count)

	var (
		code  sql.NullString
		date  sql.NullString
		red	  sql.NullString
		blue  sql.NullString
		blue2 sql.NullString
		sales sql.NullString
		poolMoney sql.NullString
		firstCount sql.NullString
		firstMoney sql.NullString
		secondCount sql.NullString
		secondMoney sql.NullString
		thirdCount sql.NullString
		thirdMoney sql.NullString
	)
	rows, err := this.dao.DB.Query(sqlStr)
	if err != nil {
		log.Error(sqlStr,zap.Error(err))
		return nil,ecode.LotteryListQueryError
	}
	defer rows.Close()

	for rows.Next() {
		err = rows.Scan(&code, &date, &red, &blue, &blue2, &sales, &poolMoney, &firstCount,
			&firstMoney, &secondCount, &secondMoney, &thirdCount, &thirdMoney)
		if err != nil {
			log.Error("rows.Scan error",zap.Error(err))
			continue
		}
		dlt :=&m.Lottery{Name: "大乐透",Type:1}
		dlt.Code = code.String
		dlt.Date = date.String
		dlt.Red = strings.Split(red.String,",")
		dlt.Blue = []string{blue.String,blue2.String}

		dlt.Sales = ts.Str2Int64(sales.String)
		dlt.PoolMoney =ts.Str2Int64(poolMoney.String)
		dlt.FirstCount = ts.Str2Int64(firstCount.String)
		dlt.FirstMoney = ts.Str2Int64(firstMoney.String)
		dlt.SecondCount = ts.Str2Int64(secondCount.String)
		dlt.SecondMoney = ts.Str2Int64(secondMoney.String)
		dlt.ThirdCount = ts.Str2Int64(thirdCount.String)
		dlt.ThirdMoney = ts.Str2Int64(thirdMoney.String)
		dltList = append(dltList,dlt)
	}
	err = rows.Err()
	if err != nil {
		log.Error("rows. error",zap.Error(err))
		return nil,ecode.LotteryListQueryError
	}
	return
}

